import { createRouter, createWebHistory } from 'vue-router'
import login from '@/views/login'
import adindex from '@/views/adminindex'
import user from '@/views/user'
import Cookies from 'js-cookie'
import axios from 'axios'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/index',
    name: 'index',
    component: adindex,
    meta: { isAuth: true, title: '主页' },
    children: [
      {
        path: '/index/user',
        name: 'user',
        component: user
      },
      {
        path: 'usermsg',
        component: () => import('@/views/usermsg.vue')
      },
      {
        path: 'audit',
        component: () => import('@/views/audit.vue')
      },
      {
        path: 'liuyan',
        component: () => import('@/views/liuyan.vue')
      },
      {
        path: '/index',
        redirect: '/index/user'
      }
    ]
  },
  {
    path: '/:',
    redirect: 'index'
  }
  // {
  //   path: '/login',
  //   name: 'Login',
  //   // component: Login
  //   // component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  // }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
router.beforeEach((to, from, next) => {
  const username = Cookies.get('username')
  const userrole = Cookies.get('userrole')
  if (to.meta.isAuth) {
    if (username && userrole) {
      next() // 放行
    } else {
      Cookies.remove('username')
      axios.get('/api/logout')
      router.push('/login')
      // alert('请先登录')
    }
  } else {
    // 否则，放行
    next()
  }
})
export default router
